<?php

namespace addons\litestore\controller\api;

use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;
use addons\third\model\Third;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\litestore\model\User;
use think\Db;

class Order extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['callback_for_wxapp', 'callback_for_wxgzh'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new Litestoreorder;

    }

    public function buyNow()
    {
        $goods_id = $this->request->request('goods_id');
        $goods_num = $this->request->request('goods_num');
        $goods_sku_id = $this->request->request('goods_sku_id');


        $order = $this->model->getBuyNow($this->user_id, $goods_id, $goods_num, $goods_sku_id);
        $order['score'] = $this->auth->score;
        #获取积分
        $integralOff = Db::table('fa_config')->where('name', '=', 'integralOff')->value('value');
        $integral = Db::table('fa_config')->where('name', '=', 'integralTormb')->value('value');
        $order['integralMsg'] = "积分兑换比例为" . $integral . ":1";
        $order['integralOff'] = $integralOff;
        $order['integral'] = $integral;
        return $this->success('获取成功', $order);
    }

    public function buyNow_pay()
    {
        $goods_id = $this->request->request('goods_id');
        $goods_num = $this->request->request('goods_num');
        $goods_sku_id = $this->request->request('goods_sku_id');
        $use_score = $this->request->request('score');
        if ($use_score > $this->auth->score) {
            return $this->error("使用积分超过已有积分");
        }
        $order = $this->model->getBuyNow($this->user_id, $goods_id, $goods_num, $goods_sku_id, $use_score);

        if ($this->model->hasError()) {
            return $this->error($this->model->getError());
        }

        // 创建订单
        if ($this->model->order_add($this->user_id, $order)) {
            #订单创建成功 立即 扣除使用的积分数
            if ($use_score > 0) {
                User::where('id', $this->user_id)
                    ->dec('score', $order['pay_score'])
                    ->update();
            }
            #如果是全额积分支付订单则直接支付成功
            if ($order['order_pay_price'] == 0) {
                #直接改变付款状态
                $this->model->save(['id' => $this->model->id, 'pay_status' => 20, 'pay_time' => time()]);
                return $this->success('积分支付成功');
            }
            // 发起微信支付
            if ($this->request->request('type') && $this->request->request('type') == 'gzh') {
                $this->init_wx_pay_for_gzh(true);
                $this->make_wx_pay('wechat');
            } else {
                $this->init_wx_pay_for_wxapp();
                $this->make_wx_pay('wxapp');
            }
        }
        $error = $this->model->getError() ?: '订单创建失败';
        return $this->error($error);

    }

    public function Get_order_num()
    {
        $NoPayNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '10', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoFreightNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoReceiptNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '20', 'order_status' => '10', 'receipt_status' => '10'])->count();
        return $this->success('', ['NoPayNum' => $NoPayNum, 'NoFreightNum' => $NoFreightNum, 'NoReceiptNum' => $NoReceiptNum]);
    }

    public function my()
    {
        $list = $this->model->getList($this->user_id);
        return $this->success('', $list);
    }

    public function detail()
    {
        $id = $this->request->request('id');
        $order = $this->model->getOrderDetail($id, $this->user_id);
        return $this->success('', ['order' => $order]);
    }

    public function cart_pay()
    {
        $rq_data = $this->request->request();
        if (empty($rq_data['ids'])) {
            return $this->error('参数错误');
        }
        #获取使用积分
        $pay_score = $rq_data['pay_score'];
        if ($pay_score > $this->auth->score) {
            return $this->error("使用积分超过已有积分");
        }
        #分解 ids
        $iDs = explode(',', $rq_data['ids']);
        unset($iDs[0]);
        $order = $this->model->getCart($this->user_id, $iDs, $pay_score);
        // 创建订单
        if ($this->model->order_add($this->user_id, $order)) {
            #订单创建成功 立即 扣除使用的积分数
            if ($pay_score > 0) {
                User::where('id', $this->user_id)
                    ->dec('score', $order['pay_score'])
                    ->update();
            }
            #清空购物车 所选商品
            $this->model->CarclearAll($this->user_id, $iDs);
            #如果是全额积分支付订单则直接支付成功
            if ($order['order_pay_price'] == 0) {
                #直接改变付款状态
                $this->model->save(['id' => $this->model->id, 'pay_status' => 20, 'pay_time' => time()]);
                return $this->success('积分支付成功');
            }

            // 发起微信支付
            if ($this->request->request('type') && $this->request->request('type') == 'gzh') {
                $this->init_wx_pay_for_gzh(true);
                $this->make_wx_pay('wechat');
            } else {
                $this->init_wx_pay_for_wxapp();
                $this->make_wx_pay('wxapp');
            }
        }
        $this->error($this->model->getError() ?: '订单创建失败');
    }

    public function finish()
    {
        $id = $this->request->post("id");
        $order = $this->model;
        if ($order->finish($this->user_id, $id)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    public function cancel()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);

        if ($order->cancel($this->user_id, $id)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    public function order_pay()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);
        if (!$order->checkGoodsStatusFromOrder($order['goods'])) {
            return $this->error($order->getError());
        }
        $this->model = $order;
        // 发起微信支付
        if ($this->request->post('type') && $this->request->post('type') == 'gzh') {
            $this->init_wx_pay_for_gzh(true);
            $this->make_wx_pay('wechat');
        } else {
            $this->init_wx_pay_for_wxapp();
            $this->make_wx_pay('wxapp');
        }
    }

    private function init_wx_pay_for_gzh($Ischeck = false)
    {
        //这里首先判断 此用户是否绑定了微信公众号
        if ($Ischeck) {
            $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wechat'])->find();
            if (!$third) {
                //从这里自动绑定微信公众号的账户
                $this->error('您未绑定微信号', null, 1008);
            }
        }

        $config = get_addon_config('litestore');

        $third_config = get_addon_config('third');
        $third_options = array_intersect_key($third_config, array_flip(['wechat']));
        $third_options = $third_options['wechat'];

        $options = [
            'debug' => true,
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            'app_id' => $third_options['app_id'],
            'secret' => $third_options['app_secret'],
            'payment' => [
                'merchant_id' => $config['MCHIDGZH'],
                'key' => $config['APIKEYGZH'],
                'notify_url' => \think\Request::instance()->domain() . addon_url('litestore/api.order/callback_for_wxgzh'),
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

    private function init_wx_pay_for_wxapp()
    {
        $config = get_addon_config('litestore');
        $options = [
            'app_id' => $config['AppID'],
            'secret' => $config['AppSecret'],
            'payment' => [
                'merchant_id' => $config['MCHID'],
                'key' => $config['APIKEY'],
                'notify_url' => \think\Request::instance()->domain() . addon_url('litestore/api.order/callback_for_wxapp'),
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

    private function make_wx_pay($platform)
    {
        $third = Third::where(['user_id' => $this->user_id, 'platform' => $platform])->find();

        $payment = $this->wxapp->payment;

        $attributes = [
            'trade_type' => 'JSAPI',
            'body' => $this->model['order_no'],
            'detail' => 'OrderID:' . $this->model['id'],
            'out_trade_no' => $this->model['order_no'],
            //'total_fee'        => $this->model['pay_price'] * 100, // 单位：分
            'total_fee' => 1, // 单位：分
            'openid' => $third['openid'],
        ];
        $order = new WXPAY_ORDER($attributes);

        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            return $this->success('预支付成功', $config);
        }
        return $this->error('微信支付调用失败', $result);
    }

    public function callback_for_wxgzh()
    {
        $this->init_wx_pay_for_gzh(false);
        $response = $this->wxapp->payment->handleNotify(function ($notify, $successful) {
            $order = $this->model->payDetail($notify->out_trade_no);

            if (empty($order)) { // 如果订单不存在
                return true;
                //return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($successful) {
                $order->updatePayStatus($notify->transaction_id);
            }

            return true; // 返回处理完成
        });

        $response->send();
    }

    public function callback_for_wxapp()
    {
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function ($notify, $successful) {
            $order = $this->model->payDetail($notify->out_trade_no);

            if (empty($order)) { // 如果订单不存在
                return true;
                //return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($successful) {
                $order->updatePayStatus($notify->transaction_id);
            }

            return true; // 返回处理完成
        });

        $response->send();
    }

}
